﻿package fwk.webservices{
	
	import flash.net.*;
	import flash.xml.XMLDocument;
    import flash.events.Event;
	import flash.events.ErrorEvent;
	import flash.events.HTTPStatusEvent;
	
	
	public class WebService {
		private var urlLoaderService:URLLoader;
		public var soap12:Namespace 	= new Namespace("http://www.w3.org/2003/05/soap-envelope");
		public var xsi:Namespace 	= new Namespace("http://www.w3.org/2001/XMLSchema-instance");
		public var xsd:Namespace 	= new Namespace("http://www.w3.org/2001/XMLSchema");
		public var returnFunction:Function;
		
		public function WebService() {}
		
		public function loadWebService($feedURL:String,$returnFunction:Function,$parametro:String=null,$valor:String=null):void {
			var webMethod:String = $feedURL.split("=")[1];
			var urlRequest:URLRequest = new URLRequest($feedURL);
			returnFunction = $returnFunction;
			urlRequest.method = URLRequestMethod.POST;
			urlRequest.requestHeaders.push(new URLRequestHeader("Content-Type", "application/soap+xml; charset=utf-8"));
			urlRequest.data = returnCorrectXML(webMethod,$parametro,$valor);
			urlLoaderService = new URLLoader();
			urlLoaderService.dataFormat = URLLoaderDataFormat.TEXT;
			urlLoaderService.addEventListener("complete", onServiceLoaded);
			urlLoaderService.addEventListener("ioerror", ifServiceFailed);
			urlLoaderService.load(urlRequest);
		}
		
		public function onServiceLoaded(e:Event):void {
			var d:XML = new XML(urlLoaderService.data);
			returnFunction(d);
			urlLoaderService.data = null;
		}
		
		public function ifServiceFailed(e:ErrorEvent):void {
			trace("Couldn't load "+ returnFunction +" because ::: " + e);
		}
		
		/*	--------------------------------------------------------------	*/
		/*	REPOSITORY OF FEED CONFIGURATIONS								*/
		/*	--------------------------------------------------------------	*/
		public function returnCorrectXML(metodo:String,parametro:String,valor:String):XML {
			
			var rXML:XML = 
				<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
					<soap12:Body/>
				</soap12:Envelope>
				;
				
			if (parametro != null) {
				rXML.soap12::Body.appendChild( 
					<{metodo} xmlns="http://tempuri.org/">
						<{parametro}>{valor}</{parametro}>
					</{metodo}>
				);
				
			}
			else {
				rXML.soap12::Body.appendChild(
					<{metodo} xmlns="http://tempuri.org/" />
				);
			}
			return rXML;
		}
	}
}